﻿using UnityEngine;
using System.IO;
/// <summary>
/// Author Anson.zhu
/// Pb 存读取file
/// </summary>
public static class ProtoLoader
{
//    private static CSProtoSerializer m_serializer = new CSProtoSerializer();

    public static T loadObjectFromResource<T>(string resourcePath)
    {
        TextAsset objectAsset = Resources.Load(resourcePath, typeof(TextAsset)) as TextAsset;
        
        if(objectAsset == null)
        {
            return default(T);
        }

        T deserializeObject = default(T);

        using (MemoryStream m = new MemoryStream(objectAsset.bytes))
        {
            deserializeObject = (T)ProtoBuf.Serializer.Deserialize<T>(m);//, null, typeof(T));

        }
        return deserializeObject;
    }
    
    public static T loadObjectFromPath<T>(string path)
    {
        if(!File.Exists(path))
        {
            return default(T);
        }

        T deserializeObject = default(T);

        using (FileStream f = new FileStream(path, FileMode.Open))
        {
            deserializeObject = (T)ProtoBuf.Serializer.Deserialize<T>(f);
        }

        return deserializeObject;
    }

    public static void saveObjectToPath<T>(string objectPath, string fileName, T serializeObject)
    {
        if (!Directory.Exists(objectPath)) //判路径存在
        {
            Directory.CreateDirectory(objectPath);
        }

        using (FileStream f = new FileStream(objectPath + fileName, FileMode.OpenOrCreate))
        {
            ProtoBuf.Serializer.Serialize(f, serializeObject);
        }
    }

    public static byte[] serializeProtoObject<T>(T obj)
    {
        using(MemoryStream m = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(m, obj);
            return m.ToArray();
        }
    }

    public static T deserialzeProtoObject<T>(byte[] bytes)
    {
        using(MemoryStream m = new MemoryStream(bytes))
        {
            return (T)ProtoBuf.Serializer.Deserialize<T>(m);
        }
    }
}